package worker

import (
	"NovelBook/logic/book"
	"NovelBook/models/db_models"
	"NovelBook/utils/auth"
	"NovelBook/utils/response"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

func CreateBooks(c *gin.Context) {
	id_any, exit := c.Get(auth.WorkerIDKey)
	id := id_any.(uint)
	if !exit || id < 0 {
		response.Fail(c, http.StatusBadRequest, response.CodeTokenInvalid)
		return
	}
	var books []db_models.Books
	err := c.ShouldBindJSON(&books)
	if err != nil {
		response.Fail(c, http.StatusBadRequest, response.CodeParamsInvalid)
		log.Println("bind err : ", err)
		return
	}
	err = book.CreateBooks(books)
	if err != nil {
		log.Println(err)
		split := strings.Split(err.Error(), " ")
		if split[1] == "1062" {
			response.FailWithMsg(c, http.StatusBadRequest, response.CodeParamsInvalid, "BOOK EXIST")
			return
		}
		response.FailWithMsg(c, http.StatusServiceUnavailable, response.CodeSystemBusy, "database insert error")
		return
	}
	response.Success(c, nil)
}
